package com.zg.system.attach;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zg.common.core.R;
import com.zg.common.core.dao.system.SysAttach;
import com.zg.common.core.dao.system.SysAttachDao;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class AttachController {
    private final SysAttachDao attachDao;

    @PostMapping("/attach/add")
    public R add(@RequestBody List<SysAttach> list) {
        list.stream().forEach(obj -> {
            obj.setSearchStr(obj.getCode() + obj.getTableName() + obj.getTableId());
            attachDao.save(obj);
        });
        return R.success();
    }

    @PostMapping("/attach/del")
    public R del(@RequestBody List<Long> ids) {
        attachDao.removeBatchByIds(ids);
        return R.success();
    }

    @GetMapping("/attach/page")
    public R page(String searchStr, String tableName, String code, Long tableId, Integer page, Integer pageSize) {
        IPage<SysAttach> pageParam = new Page<>(page, pageSize);
        QueryWrapper<SysAttach> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SysAttach> lambdaQueryWrapper = queryWrapper.lambda()
                .eq(SysAttach::getTableName, tableName)
                .eq(SysAttach::getTableId, tableId);
        if (StrUtil.isNotBlank(searchStr)) {
            lambdaQueryWrapper.like(SysAttach::getFileName, "%" + searchStr + "%");
        }
        if (StrUtil.isNotBlank(code) && !code.equals("all")) {
            lambdaQueryWrapper.eq(SysAttach::getCode, code);
        }
        IPage<SysAttach> result = attachDao.page(pageParam, queryWrapper);
        return R.success(result);
    }

    @GetMapping("/attach/count")
    public R countAttach(String tableName, Long tableId) {
        long count = attachDao.count(new QueryWrapper<SysAttach>()
                .lambda()
                .eq(SysAttach::getTableName, tableName)
                .eq(SysAttach::getTableId, tableId));
        return R.success(count);
    }
}
